import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

// 登录页面组件
import Login from '../views/Login.vue'

// 前台布局组件
import FrontLayout from '../layouts/FrontLayout.vue'

// 后台布局组件
import AdminLayout from '../layouts/AdminLayout.vue'

// 后台各页面组件
import Dashboard from '../views/admin/dashboard/index.vue'
import UserManagement from '../views/admin/user/index.vue'
import AdoptionPostManagement from '../views/admin/adoption-post/index.vue'
import AdoptionRecordManagement from '../views/admin/adoption-record/index.vue'
import SurrenderPostManagement from '../views/admin/surrender-post/index.vue'
import DonationManagement from '../views/admin/donation/index.vue'

// 添加宠物类别管理页面组件导入
import PetCategoryManagement from '../views/admin/pet-category/index.vue'

// 前台页面组件
import Home from '../views/front/home/index.vue'
import Adoption from '../views/front/adoption/index.vue'
import Surrender from '../views/front/surrender/index.vue'
import Donation from '../views/front/donation/index.vue'
import Profile from '../views/front/profile/index.vue'
import PetDetail from '../views/front/pet-detail/index.vue'

// 个人中心子页面
import UserInfo from '../views/front/profile/info/index.vue'
import AdoptionRecords from '../views/front/profile/adoption-records/index.vue'
import SurrenderRecords from '../views/front/profile/surrender-records/index.vue'
import DonationRecords from '../views/front/profile/donation-records/index.vue'

// 需要登录才能访问的路由
const requiresAuth = [
  '/front/surrender',
  '/front/donation',
  '/front/profile'
]

// 需要管理员权限的路由
const requiresAdmin = [
  '/admin'
]

// 仅普通用户可访问的路由（管理员不能访问）
const userOnlyRoutes = [
  '/front'
]

const routes = [
  {
    path: '/',
    redirect: '/front'  // 根路径重定向到前台首页
  },
  {
    path: '/login',
    name: 'Login',
    component: Login    // 用户登录页面
  },
  {
    path: '/front',
    name: 'Front',
    component: FrontLayout,  // 前台页面布局
    children: [
      {
        path: '',
        name: 'Home',
        component: Home  // 前台首页
      },
      {
        path: 'adoption',
        name: 'Adoption',
        component: Adoption  // 领养中心页面
      },
      {
        path: 'surrender',
        name: 'Surrender',
        component: Surrender  // 送养申请页面
      },
      {
        path: 'donation',
        name: 'Donation',
        component: Donation  // 爱心捐募页面
      },
      {
        path: 'profile',
        name: 'Profile',
        component: Profile,  // 个人中心页面
        redirect: '/front/profile/info',
        children: [
          {
            path: 'info',
            name: 'UserInfo',
            component: UserInfo  // 个人信息页面
          },
          {
            path: 'adoption-records',
            name: 'AdoptionRecords',
            component: AdoptionRecords  // 领养记录页面
          },
          {
            path: 'surrender-records',
            name: 'SurrenderRecords',
            component: SurrenderRecords  // 送养记录页面
          },
          {
            path: 'donation-records',
            name: 'DonationRecords',
            component: DonationRecords  // 捐赠记录页面
          }
        ]
      },
      {
        path: 'pet/:id',
        name: 'PetDetail',
        component: PetDetail,  // 宠物详情页面
        props: true
      }
    ]
  },
  {
    path: '/admin',
    name: 'Admin',
    component: AdminLayout,  // 后台管理页面布局
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: Dashboard  // 后台控制面板页面
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: UserManagement  // 用户管理页面
      },
      {
        path: 'adoption-posts',
        name: 'AdoptionPostManagement',
        component: AdoptionPostManagement  // 宠物领养贴管理页面
      },
      {
        path: 'adoption-records',
        name: 'AdoptionRecordManagement',
        component: AdoptionRecordManagement  // 动物领养记录管理页面
      },
      {
        path: 'surrender-posts',
        name: 'SurrenderPostManagement',
        component: SurrenderPostManagement  // 动物送养贴管理页面
      },
      {
        path: 'donations',
        name: 'DonationManagement',
        component: DonationManagement  // 爱心捐募管理页面
      },
      {
        path: 'pet-categories',
        name: 'PetCategoryManagement',
        component: PetCategoryManagement  // 宠物类别管理页面
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取用户信息
  const userInfoStr = localStorage.getItem('userInfo')
  const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
  
  // 检查是否是管理员路由
  const isAdminRoute = requiresAdmin.some(path => to.path.startsWith(path))
  if (isAdminRoute) {
    if (!userInfo) {
      ElMessage({
        message: '请先登录',
        type: 'warning',
        duration: 2000
      })
      next('/login')
      return
    }
    
    if (userInfo.role !== 'admin') {
      ElMessage({
        message: '无权访问管理后台',
        type: 'error',
        duration: 2000
      })
      next('/front')
      return
    }
    
    next()
    return
  }

  // 检查是否是仅用户可访问的路由
  const isUserOnlyRoute = userOnlyRoutes.some(path => to.path.startsWith(path))
  if (isUserOnlyRoute && userInfo?.role === 'admin') {
    ElMessage({
      message: '管理员不能访问前台页面',
      type: 'warning',
      duration: 2000
    })
    next('/admin')
    return
  }

  // 检查是否需要登录的普通路由
  const needsAuth = requiresAuth.some(path => to.path.startsWith(path))
  if (needsAuth && !userInfo) {
    ElMessage({
      message: '请先登录',
      type: 'warning',
      duration: 2000
    })
    next('/login')
    return
  }
  
  // 如果是登录页面且用户已登录，重定向到对应的首页
  if (to.path === '/login' && userInfo) {
    if (userInfo.role === 'admin') {
      next('/admin')
    } else {
      next('/front')
    }
    return
  }

  next()
})

export default router 